import { html, internalProperty, query, queryAll } from 'lit-element'
import { unsafeHTML } from 'lit-html/directives/unsafe-html'
import { BaseElement } from '../../../baseElement'
import '../../../loadable/icon'
import '../../../loadable/input'
import { defineElement } from '../../../utils'
import citySources from './citySources'
import { Styles } from './style'

const defaultHotCityName = [
  '杭州',
  '北京',
  '上海',
  '广州',
  '深圳',
  '成都',
  '重庆',
  '天津',
  '南京',
  '苏州',
  '武汉',
  '西安'
]

const hotCitys = []

const navigation = ['#']
citySources.cityList.forEach((item) => {
  const { cities, idx } = item
  navigation.push(idx)
  cities.forEach((city) => {
    if (defaultHotCityName.includes(city.name)) {
      hotCitys.push(city)
    }
  })
})

class ChooseCity extends BaseElement {
  [propName: string]: any

  private searchValue: string

  @internalProperty()
  searchCitys = []

  static get styles() {
    return Styles
  }

  dispatch(action, options) {
    this.dispatchEvent(
      new CustomEvent(action, {
        detail: options,
        bubbles: true,
        composed: true
      })
    )
  }

  __handleChoose(e) {
    const { long: longitude, lat: latitude, city, code } = e.target.dataset
    if (city) {
      this.dispatch('choose', { longitude, latitude, city, adCode: code })
    }
  }

  __handleClose() {
    this.dispatch('close', {})
  }

  __handleJump(e) {
    const { idx } = e.target.dataset
    if (idx === '#') {
      this.cityList.scrollTo(0, 0)
      return
    }

    const node: any = Array.from(this.cityIdxList).find((node: any) => {
      return node.dataset.idx === idx
    })

    this.cityContent.scrollTo(0, node.offsetTop)
  }

  handleSearch(e) {
    const val = e.detail.value
    this.searchValue = val
    this.searchCitys = []
    if (val) {
      citySources.cityList.forEach((item) => {
        const { cities, idx } = item
        if (idx === val.toUpperCase()) {
          this.searchCitys = this.searchCitys.concat(cities)
        } else {
          cities.forEach((city) => {
            const { name, pinyin } = city
            if (val === name || val === pinyin) {
              this.searchCitys.push(city)
            }
          })
        }
      })
    }
  }

  @queryAll('.city-list-title')
  cityIdxList
  @query('.choose-city-content')
  cityContent

  renderSearchList() {
    if (this.searchCitys.length) {
      return html`<div class="search-city-list" @click="${this.__handleChoose}">
        ${unsafeHTML(
          this.searchCitys
            .map((city) => {
              const { latitude, longitude, name, districtCode } = city
              return `<div class="city-list-cell" data-long="${longitude}" data-lat="${latitude}" data-city="${name}" data-code="${districtCode}">${name}</div>`
            })
            .join('')
        )}
      </div>`
    }

    return html`<div class="no-search-city-list">无结果</div>`
  }

  renderCityList() {
    return html` <div class="choose-navigation" @click="${this.__handleJump}">
        ${unsafeHTML(
          navigation
            .map(
              (idx) =>
                `<div class="navigation-cell" data-idx="${idx}">${idx}</div>`
            )
            .join('')
        )}
      </div>
      <div>
        <div class="hot-city">
          <div class="hot-city__title">热门城市</div>
          <div class="hot-city__list" @click="${this.__handleChoose}">
            ${unsafeHTML(
              hotCitys
                .map((city) => {
                  const { latitude, longitude, name, districtCode } = city
                  return `
                    <div class="hot-city__cell" data-long="${longitude}" data-lat="${latitude}" data-city="${name}" data-code="${districtCode}">${name}</div>
                  `
                })
                .join('')
            )}
          </div>
        </div>
        <div class="city-list" @click="${this.__handleChoose}">
          ${unsafeHTML(
            citySources.cityList
              .map((item) => {
                const { cities, idx } = item
                return `
                  <div class="city-list__card">
                    <div class="city-list-title" data-idx="${idx}">${idx}</div>
                    <div class="city-list-cells">
                      ${cities
                        .map((city) => {
                          const { latitude, longitude, name, districtCode } =
                            city
                          return `
                            <div class="city-list-cell" data-long="${longitude}" data-lat="${latitude}" data-city="${name}" data-code="${districtCode}">${name}</div>
                          `
                        })
                        .join('')}
                    </div>
                  </div>
                `
              })
              .join('')
          )}
        </div>
      </div>`
  }

  render() {
    return html`
      <div class="choose-city">
        <div class="choose-title">城市列表</div>
        <div class="close-wrap" @click="${this.__handleClose}">
          <img
            class="close"
            src=""
            alt=""
          />
        </div>
        <div class="search-city">
          <tiga-icon
            class="search-icon"
            type="search"
            color="#86909c"
            size="10"
          ></tiga-icon>
          <tiga-input
            class="search-city-input"
            @input="${this.handleSearch}"
            placeholder="输入城市名、拼音或字母查询"
            placeholder-style="font-size: 14px;"
          ></tiga-input>
        </div>
        <div class="choose-city-content">
          ${this.searchValue ? this.renderSearchList() : this.renderCityList()}
        </div>
      </div>
    `
  }
}

defineElement('private-choose-city', ChooseCity)
